<?php

namespace app\award;

use app\models\NewLevel;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductArea;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserLevel;
use app\services\Chain;

class Up
{
    protected $order;
    protected $user;
    protected $set;

    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->user = User::findOne(['id' => $this->order->user_id]);

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $product_id = $first_order_item->product_id;

        $is_bao = ProductArea::checkBao($product_id);
        $is_diff = ProductArea::checkDiff($product_id);

        $this->set = SetUserUp::getLastOne();

        // 必须是报单区
        if ($is_bao) {
            $this->upMyself();
            $this->quota();
        }



    }

    // 升级自己
    protected function upMyself()
    {
        $user = $this->user;

        $amount = $this->order->total_pay - $this->order->total_freight;

        if ($amount >= $this->set->vip3) {
            if ($user->level < UserLevel::$keys['vip3']) {
                $user->level = UserLevel::$keys['vip3'];
                $user->save();

            }
        }
        else if ($amount >= $this->set->vip2) {
            if ($user->level < UserLevel::$keys['vip2']) {
                $user->level = UserLevel::$keys['vip2'];
                $user->save();

            }
        }
        else if ($amount >= $this->set->vip1) {
            if ($user->level < UserLevel::$keys['vip1']) {
                $user->level = UserLevel::$keys['vip1'];
                $user->save();
            }
        }

    }


    // 处理配额
    public function quota()
    {
        if ($this->order->quota_type > 0) {
            $product_id = OrderItem::find()
                ->where(['order_id' => $this->order->id])
                ->select(['product_id'])
                ->scalar();
            $product = Product::findOne(['id' => $product_id]);

            if ($this->order->quota_type == 1) {
                $this->user->quota1 += $product->quota_1;
                $this->user->save();
            }
            if ($this->order->quota_type == 2) {
                $this->user->quota2 += $product->quota_2;
                $this->user->save();
            }
        }
    }

}